#include "../../include/log/log.h"
#include <thread>

void Log::init()
{
    std::thread t(threadWriteLog);
    t.detach();
    std::string file = "./server.log";
    outFp.open(file, std::ios::out);
    if(!outFp)
    {
        std::cout << "error open serverLog fail" << std::endl;
    }
    outFp << "open serverLog success start write Log" << std::endl;
    std::cout << "open serverLog success start write Log" << std::endl;
}

void Log::writeLog(LogState state, const char* format, ...)
{
    std::lock_guard<std::mutex> lock(m_mutex);
    std::string writeLog;
    va_list argp;
    va_start(argp, format);
    vsnprintf(buffer, MAX_BUFFER_SIZE, format, argp);
    va_end(argp);

    switch (state)
    {
        case LogState::infoLog:
            std::cout << "[InfoLog]: ";
            writeLog += "[InfoLog]: ";
            break;
        case LogState::errorLog:
            std::cout << "[ErrorLog]: ";
            writeLog += "[InfoLog]: ";
            break;
    }
    std::cout << buffer << std::endl;
    writeLog += buffer;
    if(writeQueue.size() <= maxWriteQueue)
    {
        writeQueue.push(writeLog);
        sem_post(&sem);
    }
    else
    {
        outFp << writeLog << std::endl;
    }
}

void Log::flush()
{
    std::lock_guard<std::mutex> lock(m_mutex);
    outFp.flush();
}

Log::~Log()
{
    outFp.close();
}

void Log::logToFile()
{
    sem_wait(&sem);
    std::lock_guard<std::mutex> lock(m_mutex);
    std::string content = writeQueue.front();
    writeQueue.pop();
    outFp << content << std::endl;
}